<template>
  <!-- width="100%" -->
  <a-modal
    title="月度预算详情"
    :visible="visible"
    :destroyOnClose="true"
    :maskClosable="false"
    @cancel="handleCancel"
    width="95%"
    :footer="null">
    <a-spin :spinning="spinning" tip="加载中...">
      <a-button type="primary" @click="onExcel">
        导出
      </a-button>
      <a-table
        :columns="columns"
        bordered
        :data-source="newSource"
        :scroll="{ x: 800, y: 500 }"
        :pagination="false"
        :rowKey="(record, index) => { return record.projectId }"
        :defaultExpandAllRows="true"
        v-if="newSource.length">
        <template slot="promote" slot-scope="text,record">
          <span>
            {{ rateCompute(record.preActual, record.budget) }}
          </span>
        </template>
        <template slot="budget" slot-scope="text,record">
          <div class="editable-cell">
            <div class="editable-cell-text-wrapper">
              {{ text || ' ' }}
            </div>
          </div>
        </template>
      </a-table>
    </a-spin>
  </a-modal>
</template>

<script>
import { getBudgetsLaunch, addBudgets, detailBudgets, editBudgets, getExportExcel } from '@/api/budget'
import { cloneDeep } from 'lodash-es'
// import { exportExcelFinal } from '@/utils/exportExcel'
export default {
    data () {
        return {
            visible: false,
            dataSource: [],
            newSource: [], // 变化的源数据
            spinning: true,
            columns: [], // 头部表单

            editableData: {}, // 修改的位置数据
            previousData: {}, // 上一次的值
            editable: false, // 是否编辑

            // 接口参数
            addForm: {
                storeId: '',
                budgetType: '',
                budgetDate: '',
                title: '',
                description: ''
            },
            visibleBtn: false,
            loadingBtn: false,
            projects: [],
            rowData: '',

            ExcelList: []
        }
    },
    methods: {
        onExcel () {
            getExportExcel(this.rowData.budgetId).then(res => {
                const dataExcel = new Blob([res], {
                    type: 'application/vnd.ms-excel'
                })
                const downloadUrl = window.URL.createObjectURL(dataExcel)
                const anchor = document.createElement('a')
                anchor.href = downloadUrl
                anchor.download = '月度预算.xls' // 表格名称.文件类型
                anchor.click()
                window.URL.revokeObjectURL(res) // 消除请求接口返回的list数据
            })
        },
        // 计算比率
        // 本月比上月情况=（本月数字-上月数字）/上月数字，如果本月大于上月，结果就是正数，即上升，反之为下降
        rateCompute (a, b) {
            if (a > 0 && b > 0) {
                if (a < b) return ((((b - a) / a) * 100).toFixed(2)) + '%'
                else if (b < a) '-' + ((((b - a) / a) * 100).toFixed(2)) + '%'
                else return '0%'
            } else {
                if (a == 0 && b > a) return '100%'
                else return '0%'
            }
        },
        edit (row) {
            this.editable = true
            this.editableData[row.projectId] = cloneDeep(row)
        },
        save (row) {
            this.editable = false

            this.calculate(row)
        },
        // 计算
        calculate (row) {
            // // 修改当前数据的值
            // this.getObj(this.newSource, row.projectId, Number(row.budget))
            // // 获取兄弟节点的父级id
            // let brotherParentId = row.parentProjectId
            // // 获取兄弟节点数据
            // let brotherParentArr =this.getBrotherParentId(this.newSource, brotherParentId)
            // // console.log(brotherParentArr)
            // // 兄弟数组的和  相差值
            // let ParentVal = brotherParentArr.reduce((accumulator, currentValue) => Number(accumulator) + Number(currentValue));
            // // console.log(ParentVal)
            // // 相关连的数据包括原来未改变的初始值
            // let joinedArr = this.get_level_all(this.dataSource, row.projectId)
            // joinedArr = joinedArr.filter(item => item.projectId != row.projectId)

            // // 处理直系父级
            // // joinedArr = joinedArr.filter(item => item.projectId != row.parentProjectId)
            // // this.getObj(this.newSource, row.parentProjectId, ParentVal)

            // // 相差值
            // joinedArr.forEach((item) => {
            //     this.getParentId(this.newSource, item.projectId,Number(ParentVal))
            // });

            // delete this.editableData[row.projectId];
            this.fun1(row)
        },
        fun1 (row) {
            const Obj = this.getObj(this.newSource, row.projectId, Number(row.budget))
            this.fun2(row)
        },
        fun2 (row) {
            // 获取兄弟节点的父级id
            const brotherParentId = row.parentProjectId
            // 获取兄弟节点数据
            const brotherParentArr = this.getBrotherParentId(this.newSource, brotherParentId)
            // console.log(brotherParentArr)
            // 兄弟数组的和  相差值
            const ParentVal = brotherParentArr.reduce((accumulator, currentValue) => Number(accumulator) + Number(currentValue))
            if (ParentVal) {
                this.fun3(row, ParentVal)
            }
        },
        fun3 (row, ParentVal) {
            console.log(this.newSource)
            // 相关连的数据包括原来未改变的初始值
            let joinedArr = this.get_level_all(this.dataSource, row.projectId)
            joinedArr = joinedArr.filter(item => item.projectId != row.projectId)
            const _this = this
            // setTimeout(() => {
            // 相差值
            joinedArr.forEach((item) => {
                _this.getParentId(_this.newSource, item.projectId, Number(ParentVal))
            })
            delete _this.editableData[row.projectId]
            // }, 200)
        },
        // 根据id ，找到当前元素的对象，并进行赋值
        getObj (data, id, val) {
            data.find((item) => {
                if (item.projectId === id) {
                    if (val == 0) item.budget = '0'
                    else item.budget = Number(val)

                    item.promote = this.rateCompute(Number(item.preActual), Number(item.budget))
                    return true
                } else if (item.children != null && item.children.length > 0) {
                    this.getObj(item.children, id, val)
                }
                return false
            })
        },
        // 根据id，找到所有的上级id
        get_level_all (data, id, arr = []) {
            data.find((item) => {
                if (item.projectId === id) {
                    arr.push(item)
                    return true
                } else if (item.children != null && item.children.length > 0) {
                    arr = this.get_level_all(item.children, id, arr)
                    if (arr.length) {
                        arr.push(item)
                        return true
                    } else {
                        return false
                    }
                }
                return false
            })
            return arr
        },
        // 根据id，找到所有的同级数据
        getBrotherParentId (data, id, arr = []) {
            data.find((item) => {
                if (item.parentProjectId == id) {
                    // 收支类型，1：收入，2：支出，3：其它
                    // 支出:减
                    arr.push((item.inOrOut == '2' ? Number(('-' + item.budget)) : Number(item.budget)))
                } else if (item.children != null && item.children.length > 0) {
                    this.getBrotherParentId(item.children, id, arr)
                }
            })
            return arr
        },
        // 根据相差值遍历相关的父级或祖级
        getParentId (arr, id, numDiffer) {
            // arr.forEach(item => {
            //     if (item.projectId == id) {
            //         item.budget = Number(item.budget) + Number(numDiffer)
            //         item.promote = this.rateCompute(item.preActual, item.budget)

            //     }
            //     if (item.children != null && item.children.length > 0) {
            //         this.getParentId(item.children, id, numDiffer)
            //     }
            // })

            arr.forEach(item => {
                if (item.projectId == id) {
                    item.budget = Number(this.sumChildren(item.children))
                    item.promote = this.rateCompute(item.preActual, item.budget)
                }
                if (item.children != null && item.children.length > 0) {
                    this.getParentId(item.children, id, numDiffer)
                }
            })
        },
        // 获取子集得计算和
        sumChildren (children) {
            let sum = 0
            children.map(item => {
                console.log(item.budget)
                sum += item.inOrOut == '2' ? Number(('-' + item.budget)) : Number(item.budget)
            })
            return sum
        },
        // 取消
        cancel (key) {
            this.editable = false
            delete this.editableData[key]
        },
        // 显示
        open (par) {
            this.dataSource = []
            this.columns = []
            this.visible = true
            this.addForm = par
            this.rowData = par
            detailBudgets(par.budgetId).then(res => {
                if (res.code == 200) {
                    const sheet = res.data.sheet
                    this.addForm.title = sheet.title
                    const headers = sheet.headers
                    headers.map(item => {
                        if (item.hidden == false) this.operator(item)
                    })
                    this.columns.push({
                        title: '提升比率',
                        dataIndex: 'promote',
                        key: 'promote',
                        align: 'left',
                        width: 120,
                        scopedSlots: { customRender: 'promote' }
                    })
                    const row = sheet.rows
                    this.newSource = row
                    this.handNull(this.newSource)
                    console.log(this.newSource)
                    // this.dataSource = row
                    this.dataSource = this.newSource
                    this.spinning = false
                }
            })
        },
        // 子集没数据，赋值为空 null
        handNull (data) {
            data.forEach((item) => {
                item.promote = this.rateCompute(item.preActual, item.budget)

                if (item.children.length == 0) {
                    item.children = null
                } else {
                    this.handNull(item.children)
                }
            })
        },
        // columns 表头赋值
        operator (item) {
            const obj = {}
            if (item.columnId == 'projectName') {
                obj['title'] = item.name
                obj.dataIndex = 'name'
                obj.key = 'name'
                obj.align = 'left'
            } else if (item.columnId == 'preActual') {
                obj['title'] = item.name
                obj.dataIndex = 'preActual'
                obj.key = 'preActual'
                obj.align = 'left'
                obj.width = 200
            } else if (item.columnId == 'budget') {
                obj['title'] = item.name
                obj.dataIndex = 'budget'
                obj.key = 'budget'
                obj.align = 'left'
                obj.width = 200
                obj.scopedSlots = { customRender: 'budget' }
            } else return
            this.columns.push(obj)
        },
        // 关闭
        handleCancel () {
            this.visible = false
            this.editable = false
            this.$emit('close')
        },
        // 确认
        handleSubmit () {
            this.loadingBtn = true
            this.visibleBtn = true
            this.getArr(this.newSource)
            if (this.projects.length == 0) return

            const { budgetType, budgetDate, description, title, storeId } = this.addForm
            const par = {
                budgetType,
                budgetDate,
                projects: this.projects,
                description,
                title,
                storeId
            }
            if (this.mode == 'edit') par.budgetId = this.rowData.budgetId
            const Api = this.mode == 'add' ? addBudgets : editBudgets
            Api(par).then(res => {
                if (res.code === 200) {
                    this.$notification['success']({
                        message: '提示',
                        description: '保存成功！',
                        duration: 8
                    })
                    this.visible = false
                    this.$emit('success')
                } else {
                    this.$notification['error']({
                        message: '提示',
                        description: res.message,
                        duration: 8
                    })
                }
                this.visibleBtn = false
                this.loadingBtn = false
            })
        },
        // 遍历表格并处理
        getArr (arr) {
            arr.map(item => {
                this.projects.push({ projectId: item.projectId, budgetAmount: item.budget })
                if (item.children != null && item.children.length > 0) {
                    this.getArr(item.children)
                }
            })
        }

    }
}
</script>
<style scoped></style>
